package com.ray.utils;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/webSocket")
public class Websocket {

    private Session session;

    private static CopyOnWriteArraySet<Websocket> webSocketSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this);
        System.out.println("【websocket消息】有新的连接，总数："+webSocketSet.size());
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        System.out.println("【websocket消息】断开连接，总数："+webSocketSet.size());
    }

    @OnMessage
    public void OnMessage(String message){
        System.out.println("【websocket消息】收到客户端发来的消息："+message);
    }

    public void sendMessage(String message){
        for(Websocket websocket: webSocketSet){
            System.out.println("【websocket消息】广播消息："+message);
            try {
                websocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
